# -*- coding: utf-8 -*-
from flask import Flask, g, send_from_directory
import os
from datetime import timedelta
from dotenv import load_dotenv
from flask_login import LoginManager

from app.utils.db import db
from config import config

# 创建登录管理器
login_manager = LoginManager()

# 用户加载函数
@login_manager.user_loader
def load_user(user_id):
    from app.services.user_service import UserService
    return UserService.get_user_by_id(int(user_id))

def create_app(config_name=None):
    """
    应用工厂函数，创建Flask应用实例
    :param config_name: 配置名称
    :return: Flask应用实例
    """
    # 加载环境变量
    load_dotenv()
    
    # 创建应用实例
    app = Flask(__name__, 
                static_folder='static',  # 指定静态文件夹
                template_folder='templates')  # 指定模板文件夹
    
    # 配置应用
    if not config_name:
        config_name = os.environ.get('FLASK_ENV', 'default')
    app.config.from_object(config[config_name])
    
    # 会话配置
    app.permanent_session_lifetime = timedelta(days=7)  # 设置会话过期时间为7天
    
    # 初始化数据库
    db.init_app(app)
    
    # 初始化Flask-Login
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    
    # 注册蓝图
    with app.app_context():
        # 注册主页蓝图（最先注册，确保其路由优先级最高）
        from app.controller.index import index_bp
        app.register_blueprint(index_bp)
        
        # 注册认证蓝图
        from app.controller.auth import auth_bp
        app.register_blueprint(auth_bp)
        
        # 注册搜索蓝图
        from app.controller.search import search_bp
        app.register_blueprint(search_bp)
        
        # 注册网盘搜索蓝图
        from app.controller.pansou import pansou_bp
        app.register_blueprint(pansou_bp)
        
        # 注册图片素材搜索蓝图
        from app.controller.picture import picture_bp
        app.register_blueprint(picture_bp)
        
        # 注册音乐搜索蓝图
        from app.controller.music import music_bp
        app.register_blueprint(music_bp)
        
        # 注册AI助手蓝图
        from app.controller.ai_assistant import ai_assistant_bp
        app.register_blueprint(ai_assistant_bp)
        
        # 注册影视蓝图
        from app.controller.movie import movie_bp
        app.register_blueprint(movie_bp)
        
        # 注册管理蓝图
        from app.controller.admin.users import users_admin_bp
        from app.controller.admin.movies import movies_admin_bp
        app.register_blueprint(users_admin_bp)
        app.register_blueprint(movies_admin_bp)
    
    # 请求处理前钩子，确保数据库连接
    @app.before_request
    def before_request():
        g.db = db
    
    @app.route('/ads.txt')
    def serve_ads():
        return send_from_directory(app.static_folder, 'ads.txt')
    
    @app.route('/.well-known/pki-validation/CE4C8AEC7573761B5DE836AAF21DCF62.txt')
    def serve_ssl_verify():
        return send_from_directory(app.static_folder, '.well-known/pki-validation/CE4C8AEC7573761B5DE836AAF21DCF62.txt')
    
    return app
